package com.team9.fitness.service;

import com.team9.fitness.entity.UserFoodRecord;
import com.team9.fitness.entity.FoodRecordItem;
import com.team9.fitness.mapper.UserFoodRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class UserFoodRecordService {

    private final UserFoodRecordMapper recordMapper;

    public UserFoodRecordService(UserFoodRecordMapper recordMapper) {
        this.recordMapper = recordMapper;
    }

    @Transactional
    public UserFoodRecord saveFoodRecord(Long userId, List<FoodRecordItem> items) {
        // 计算总热量
        int totalCalories = items.stream().mapToInt(FoodRecordItem::getCalories).sum();

        // 创建记录
        UserFoodRecord record = new UserFoodRecord();
        record.setUserId(userId);
        record.setRecordDate(LocalDate.now());
        record.setTotalCalories(totalCalories);

        // 插入主记录
        recordMapper.insert(record);

        // 插入食物项
        recordMapper.insertRecordItems(record.getId(), items);

        record.setItems(items);
        return record;
    }

    public List<UserFoodRecord> getUserFoodHistory(Long userId) {
        List<UserFoodRecord> records = recordMapper.selectByUserId(userId);

        // 为每个记录加载食物项
        for (UserFoodRecord record : records) {
            List<FoodRecordItem> items = recordMapper.selectItemsByRecordId(record.getId());
            record.setItems(items);
        }

        return records;
    }
}
